import { Injectable } from '@nestjs/common';
import { CaptchaService } from '@app/utils/captcha/captcha.service';
import { Captcha } from '@app/utils/captcha/interface/auth.dto';
import { User, UserDocument } from '@app/database/schemas/user.schema';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { UserDto } from './dto/login.dto';
import { compareSync } from 'bcryptjs';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(
    private readonly captchaService: CaptchaService,
    private readonly jwtService: JwtService,
    @InjectModel('User')
    private readonly userModel: Model<UserDocument>,
  ) {}

  genCaptcha(): Captcha {
    return this.captchaService.genCaptcha();
  }

  checkCaptcha(captcha: Captcha): boolean {
    return this.captchaService.checkCaptcha(captcha);
  }

  async validateUser(
    username: string,
    password: string,
  ): Promise<UserDocument> {
    const user = await this.userModel.findOne({ username }).select('+password');
    if (user && compareSync(password, user.password)) {
      delete user.password;
      return user;
    }
    return null;
  }

  login(userDto: UserDto) {
    const payload = { _id: userDto._id };
    return {
      token: this.jwtService.sign(payload),
    };
  }

  async init() {
    const user = {
      username: 'admin',
      password: '123456',
      grant: 1,
      tel: 11122223333,
      address: 'admin',
    };
    await this.userModel.create(user);
    return {
      message: '初始化成功',
    };
  }
}
